package ms.spm.implement;

import ms.jacrim.framework.XmlConfiguration;
import ms.spm.IAppContext;
import ms.spm.ServiceProvider;
import ms.utils.XmlFile;

public class SimpleAppContext implements IAppContext {

	private String name;
	private IAppContext parent;
	private ServiceProvider services;
	
	public static IAppContext createRootContext() throws Exception {
		IAppContext context = new ms.spm.implement.SimpleAppContext(null, "$root");
		context.addService(new XmlConfiguration(new XmlFile("conf/jacrim.config.xml")));
		context.addService(new XmlActionCreator(context));
		return context;
	}
	
	public SimpleAppContext(IAppContext parentContext, String name) {
		this.name = name;
		parent = parentContext;
		services = new SimpleServiceProvider();
	}
	
	@Override
	public String Name() {
		return name;
	}

	@Override
	public IAppContext ParentContext() {
		return parent;
	}

	@Override
	public IAppContext Root() {
		return parent != null ? parent : parent.Root();
	}

	@Override
	public IAppContext createChildContext(String name) {
		return new SimpleAppContext(this, name);
	}

	@Override
	public void addService(Object svcInstance) {
		services.addService(svcInstance);
	}

	@Override
	public <T> T getService(Class<T> svcContract) {
		T result = services.getService(svcContract);
		return result != null ? result : parent != null ? parent.getService(svcContract) : null;
	}

}
